package org.finesys.common.redis.core.event.listener;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisKeyExpiredEvent;
import org.springframework.data.redis.listener.KeyspaceEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.listener.Topic;

public abstract class AbstractKeySpaceEventMessageListener extends KeyspaceEventMessageListener
		implements ApplicationEventPublisherAware {

	protected ApplicationEventPublisher publisher;

	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
		this.publisher = applicationEventPublisher;
	}

	public AbstractKeySpaceEventMessageListener(RedisMessageListenerContainer listenerContainer) {
		super(listenerContainer);
	}

	@Override
	protected void doRegister(RedisMessageListenerContainer container) {
		container.addMessageListener(this, getKeyEventTopic());
	}

	@Override
	protected void doHandleMessage(Message message) {
		publishEvent(new RedisKeyExpiredEvent<>(message.getBody()));
	}

	protected abstract Topic getKeyEventTopic();

	protected void publishEvent(RedisKeyExpiredEvent event) {
		if (publisher != null) {
			publisher.publishEvent(event);
		}
	}

}
